package com.io.IO;

import java.io.*;

/**
 * 字节流
 *文件夹拷贝
 *
 * @author jiangbang
 * @date 2016/6/2
 */
public class byteDemo2 {

    public static void main(String[] args) {
        //源文件
        String srcPath = "d:/demo";
        //目标文件
        String destPath = "d:/demo/test";
        File src = new File(srcPath);
        File dest = new File(destPath);
        if (src.isDirectory()){  //是文件夹
            dest = new File(destPath,src.getName());
        }
        delete(srcPath);
    }



    /**
     * 拷贝文件夹细节
     * @param src
     * @param dest
     */
    public static void copyDirDetail( File src, File dest){
        if(src.isFile()){//文件
            //2.选择流
            OutputStream os = null;//文件输出流  outputstream FileOutputStream
            InputStream is = null;//文件输日流  InputStream FileInputStream
            try {
                //拷贝操作
                is = new FileInputStream(src);
                os = new FileOutputStream(dest);
                int len = 0;
                byte[] bytes = new byte[100];
                while(-1!=(len=is.read(bytes))){
                    os.write(bytes,0,len);
                }
                os.flush();
                is.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(src.isDirectory()){ //文件夹
            dest = new File(dest,src.getName());
            if(dest.getAbsolutePath().contains(src.getAbsolutePath())){ //父目录不能拷贝到子目录中
                return;
            }
               // 确保文件夹存在
                dest.mkdirs();
                //获取下一级目录|文件
                for(File sub:src.listFiles()){
                    copyDirDetail(sub,new File(dest,sub.getName()));
                }
        }
    }


    /**
     * 删除文件夹下所有文件
     * @param delpath
     */
    public static void delete(String delpath){
        File file = new File(delpath);
        //不是文件夹，直接删除
        if(!file.isDirectory()){
           file.delete();
        }else if(file.isDirectory()){
            String[] filelist = file.list();
            for(int i=0;i<filelist.length;i++){
                File delFile = new File(delpath + "\\" + filelist[i]);
                if(!delFile.isDirectory()){
                    delFile.delete();
                }else if(delFile.isDirectory()){
                    delete(delpath + "\\" + filelist[i]);
                }
            }
        }
        file.delete();
    }

}
